package cn.com.klun.logic;

import cn.com.klun.tjy.base.ILogics;
import cn.com.klun.tjy.base.TaskConstants;
import cn.com.klun.tjy.common.constant.ResultEnum;
import cn.com.klun.tjy.common.util.DateUtils;
import cn.com.klun.tjy.dao.entity.TblAllStockInfo;
import cn.com.klun.tjy.dao.entity.TblSpiderExceptionInfo;
import cn.com.klun.tjy.dao.entity.TblStockDayInfos;
import cn.com.klun.tjy.dao.mapper.edit.TblSpiderExceptionInfoEditMapper;
import cn.com.klun.tjy.dao.mapper.edit.TblStockDayInfosEditMapper;
import cn.com.klun.tjy.dao.mapper.ser.TblSpiderExceptionInfoSerMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;

@Service
public class SpiderAllStoInfoLogic implements ILogics<TblAllStockInfo>{

    private Logger logger = LoggerFactory.getLogger(SpiderAllStoInfoLogic.class);

    @Autowired
    private TblStockDayInfosEditMapper tblStockDayInfosEditMapper;
    @Autowired
    private TblSpiderExceptionInfoSerMapper tblSpiderExceptionInfoSerMapper;
    @Autowired
    private TblSpiderExceptionInfoEditMapper tblSpiderExceptionInfoEditMapper;

    @Override
    @Transactional
    public ResultEnum exec(TblAllStockInfo tblAllStockInfo) throws Exception {
        String stockCode = "";
        String stockName = "";
        String EX = ""; //证券所
        String flag = "";// 根据证券所拼装不同的url
        stockCode = tblAllStockInfo.getStockCode();
        stockName = tblAllStockInfo.getName();
        EX = tblAllStockInfo.getEx();
        TblStockDayInfos tblStockDayInfos = new TblStockDayInfos();// 所有数据
        tblStockDayInfos.setStoId(EX + stockCode);
        EX = tblAllStockInfo.getEx();
        if("SH".equals(EX)||"sh".equals(EX)){
            flag = "1";//SH
        }
        if("SZ".equals(EX)||"sz".equals(EX)){
            flag = "2";//SZ
        }
        //读取网页的数据 很大可能出错 在定时任务完成后 再补充信息 直到读取完毕 或者一定的次数后必须异常报警
        if(getBaseInfo(stockCode,stockName,EX,flag,tblStockDayInfos)){
            if(getOrderInfo(stockCode,stockName,EX,flag,tblStockDayInfos)){
                if(getOtherInfo(stockCode,stockName,EX,flag,tblStockDayInfos)){
                    try{
                        tblStockDayInfosEditMapper.save(tblStockDayInfos);
                        Thread.sleep((long) (Math.random()*200 + 300));// 线程等待0.4秒
                    }catch (Exception e){
                        handleException(tblStockDayInfos);
                        return ResultEnum.PART_CASE_01;
                    }
                }else {
                    handleException(tblStockDayInfos);
                    return ResultEnum.PART_CASE_01;
                }
            }else {
                handleException(tblStockDayInfos);
                return ResultEnum.PART_CASE_01;
            }
        }else{
            handleException(tblStockDayInfos);
            return ResultEnum.PART_CASE_01;
        }
        return ResultEnum.OK;
    }
    /**
     * 读取异常信息处理
     * @param tblStockDayInfos
     */
    private void handleException(TblStockDayInfos tblStockDayInfos){
        try{
            TblSpiderExceptionInfo tblSpiderExceptionInfo = new TblSpiderExceptionInfo();
            tblSpiderExceptionInfo.setEx(tblStockDayInfos.getStoId().substring(0,2));
            tblSpiderExceptionInfo.setStockCode(tblStockDayInfos.getStoId().substring(2));
            String currDateTime = DateUtils.getCurrDateTime();
            String trnDate = DateUtils.addHours(currDateTime, 2).substring(0,8);
            tblSpiderExceptionInfo.setDate(trnDate);
            TblSpiderExceptionInfo spiderExceptionInfo1 = tblSpiderExceptionInfoSerMapper.queryObj(tblSpiderExceptionInfo);
            if(null == spiderExceptionInfo1){
                tblSpiderExceptionInfo.setLockFlag(TaskConstants.taskLockFlag.LOCK_FLAG_UNLOCK);
                tblSpiderExceptionInfoEditMapper.save(tblSpiderExceptionInfo);
            }
        }catch (Exception e){
            logger.error("*******Exception读取网页异常处理异常，异常信息{},异常股票",e.getMessage(),tblStockDayInfos.getStoId());
        }
    }

    /**
     * take base stock info
     * @param tblStockDayInfos
     */
    private boolean getBaseInfo(String stockCode, String stockName,String EX ,String flag,TblStockDayInfos tblStockDayInfos){

        String url = "";
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        StringBuffer stockInfo = new StringBuffer();
        long nowTime = System.currentTimeMillis();
        // http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?type=CT&sty=DCARQRQB&st=z&sr=&p=&ps=&token=1942f5da9b46b069953c873404aad4b5&cmd=0007252&cb=jsonpdata&callbackHq=jsonpdata&_=1517620929371
        url = "http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?type=CT&sty=DCARQRQB&st=z&sr=&p=&ps=&token=1942f5da9b46b069953c873404aad4b5&cmd="+stockCode+flag+"&cb=jsonpdata&callbackHq=jsonpdata&_="+nowTime+20;
        try {
            URL temp = new URL(url);
            URLConnection uc = temp.openConnection();
            uc.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");
            is = temp.openStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String line;
            while((line = br.readLine()) != null){
                stockInfo.append(line);
            }
            String stockBaseInfo = stockInfo.toString();
            logger.debug("date info is ******[{}}",stockBaseInfo);
            if(StringUtils.isNotEmpty(stockBaseInfo)){
                stockBaseInfo = stockBaseInfo.substring(stockBaseInfo.indexOf("[\"")+1,stockBaseInfo.lastIndexOf("]")-1).replaceAll("\"","");
            }else{
                // logger.error("没有读取到{}股票的信息",stockName+stockCode);
                return false;
            }
            String[] infos = stockBaseInfo.split(",");
            tblStockDayInfos.setEndPri(new BigDecimal("-".equals(infos[3])?"-1":infos[3]));
            tblStockDayInfos.setTrnNum(new BigDecimal("-".equals(infos[6])?"-1":infos[6]));
            tblStockDayInfos.setTrnAmount(new BigDecimal("-".equals(infos[7])?"-1":infos[7]));
            tblStockDayInfos.setStarPri(new BigDecimal("-".equals(infos[10])?"-1":infos[10]));
            tblStockDayInfos.setMaxPri(new BigDecimal("-".equals(infos[11])?"-1":infos[11]));
            tblStockDayInfos.setMinPri(new BigDecimal("-".equals(infos[12])?"-1":infos[12]));
            tblStockDayInfos.setTurnRate(new BigDecimal("-".equals(infos[13])?"-1":infos[13]));
            tblStockDayInfos.setQtityRelaRatio(new BigDecimal("-".equals(infos[14])?"-1":infos[14]));
            tblStockDayInfos.setPeRatio(new BigDecimal("-".equals(infos[15])?"-1":infos[15]));
            //jsonpdata(["2,000725,京东方A,5.68,0.01,(5)0.18,7582205,4302000384,2.65,(9)5.67,5.65,5.75,5.60,(13)2.24,0.79,22.89"])
        } catch (Exception e) {
            // logger.info("读取网页异常{}",e.getMessage());
            return false;
        } finally {
            try {
                is.close();
                isr.close();
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     * 主要获取订单信息
     * @param stockCode
     * @param stockName
     * @param EX
     * @param flag
     * @param tblStockDayInfos
     */
    private boolean getOrderInfo(String stockCode, String stockName,String EX ,String flag,TblStockDayInfos tblStockDayInfos) {
        String url = "";
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        StringBuffer orderInfo = new StringBuffer();
        // long nowTime = System.currentTimeMillis();
        url = "http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?type=CT&cmd="+stockCode+flag+"&sty=CTBFTA&st=z&sr=&p=&ps=&cb=&js=var%20tab_data=({data:[(x)]})&token=70f12f2f4f091e459a279469fe49eca5";
        try {
            URL temp = new URL(url);
            URLConnection uc = temp.openConnection();
            uc.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");
            is = temp.openStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String line;
            while((line = br.readLine()) != null){
                orderInfo.append(line);
            }
            String orderBaseInfo = orderInfo.toString();
            logger.debug("date info is ******[{}}",orderBaseInfo);
            if(StringUtils.isNotEmpty(orderBaseInfo)){
                orderBaseInfo = orderBaseInfo.substring(orderBaseInfo.indexOf("[\"")+1,orderBaseInfo.lastIndexOf("]")-1).replaceAll("\"","");
            }else{
                //logger.error("没有读取到{}股票的信息",stockName+stockCode);
                return false;
            }
            String[] infos = orderBaseInfo.split(",");
            tblStockDayInfos.setMainOutIn(new BigDecimal("-".equals(infos[5])?"-1":infos[5]));
            tblStockDayInfos.setSOrderInto(new BigDecimal("-".equals(infos[7])?"-1":infos[7]));
            tblStockDayInfos.setSOrderOut(new BigDecimal("-".equals(infos[8])?"-1":infos[8].substring(infos[8].indexOf("-")+1)));
            tblStockDayInfos.setSOrderOutIn(new BigDecimal("-".equals(infos[9])?"-1":infos[9]));
            tblStockDayInfos.setSOrderProportion(new BigDecimal("-".equals(infos[10])?"-1":infos[10].replaceAll("%","")));
            // (9)-62426.08,-14.87%,
            tblStockDayInfos.setBOrderInto(new BigDecimal("-".equals(infos[11])?"-1":infos[11]));
            tblStockDayInfos.setBOrderOut(new BigDecimal("-".equals(infos[12])?"-1":infos[12].substring(infos[8].indexOf("-")+1)));
            tblStockDayInfos.setBOrderOutIn(new BigDecimal("-".equals(infos[13])?"-1":infos[13]));
            tblStockDayInfos.setBOrderProportion(new BigDecimal("-".equals(infos[14])?"-1":infos[14].replaceAll("%","")));
            // (13)-22.09,-0.01%,
            tblStockDayInfos.setMOrderInto(new BigDecimal("-".equals(infos[15])?"-1":infos[15]));
            tblStockDayInfos.setMOrderOut(new BigDecimal("-".equals(infos[16])?"-1":infos[16].substring(infos[8].indexOf("-")+1)));
            tblStockDayInfos.setMOrderOutIn(new BigDecimal("-".equals(infos[17])?"-1":infos[17]));
            tblStockDayInfos.setMOrderProportion(new BigDecimal("-".equals(infos[18])?"-1":infos[18].replaceAll("%","")));
            // 17069.50,(18)4.06%,
            tblStockDayInfos.setLOrderInto(new BigDecimal("-".equals(infos[19])?"-1":infos[19]));
            tblStockDayInfos.setLOrderOut(new BigDecimal("-".equals(infos[20])?"-1":infos[20].substring(infos[8].indexOf("-")+1)));
            tblStockDayInfos.setLOrderOutIn(new BigDecimal("-".equals(infos[21])?"-1":infos[21]));
            tblStockDayInfos.setLOrderProportion(new BigDecimal("-".equals(infos[22])?"-1":infos[22].replaceAll("%","")));
            // (21)45378.67,10.81%,
            tblStockDayInfos.setTrnDate(infos[24].substring(0,10).replace("-",""));
            //SH
            //var tab_data=({data:["2,000725,京东方A,5.68,0.18%,
            // (5)-62448.16,10281(?),(SOI 7)1201412832,(SOO 8)-1825673600,
            // (9)-62426.08,-14.87%,(BOI)1022626208,(BOO)-1022847088,
            // (13)-22.09,-0.01%,(M)1035560672,-864865696,17069.50,
            // (18)4.06%,939587792,(L)-485801120,
            // (21)45378.67,10.81%,
            // -14.87%,2018-02-02 15:00:00"]})
            // SZ
            // var tab_data=({data:["2,000096,广聚能源,13.79,0.95%,
            // (5)-145.95,59,0,0,0.00,0.00%,3493832,-4953363,
            // (13)-145.95,-6.79%,11385882,-8934206,245.17,11.41%,6610881,-7603025,-99.21,
            // -4.62%,-6.79%,2018-02-02 15:00:00"]})
        } catch (Exception e) {
            // 处理异常 放入异常表
            // logger.info("读取网页异常{}",e.getMessage());
            return false;
        } finally {
            try {
                is.close();
                isr.close();
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
    // http://nuff.eastmoney.com/EM_Finance2015TradeInterface/JS.ashx?token=beb0a0047196124721f56b0f0ff5a27c&cb=jQuery17202780265590235217_1518327732639&id=6007071&_=1518327743449
    private boolean getOtherInfo(String stockCode, String stockName,String EX ,String flag,TblStockDayInfos tblStockDayInfos) {
        String url = "";
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        StringBuffer orderInfo = new StringBuffer();

        long nowTime = System.currentTimeMillis();
        url = "http://nuff.eastmoney.com/EM_Finance2015TradeInterface/JS.ashx?token=beb0a0047196124721f56b0f0ff5a27c&cb=jQuery17202780265590235217_"+nowTime+1+"&id="+stockCode+flag+"&_="+nowTime+22;
        try {
            URL temp = new URL(url);
            URLConnection uc = temp.openConnection();
            uc.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");
            is = temp.openStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String line;
            while((line = br.readLine()) != null){
                orderInfo.append(line);
            }
            String orderBaseInfo = orderInfo.toString();
            logger.debug("date info is ******[{}}",orderBaseInfo);
            if(StringUtils.isNotEmpty(orderBaseInfo)){
                orderBaseInfo = orderBaseInfo.substring(orderBaseInfo.indexOf("[\"")+1,orderBaseInfo.lastIndexOf("]")-1).replaceAll("\"","");
            }else{
                logger.error("没有读取到{}股票的信息",stockName+stockCode);
                return false;
            }
            String[] infos = orderBaseInfo.split(",");
            tblStockDayInfos.setPbRatio(new BigDecimal("-".equals(infos[43])?"-1":infos[43]));//市净
            tblStockDayInfos.setAllMarketVal(new BigDecimal("-".equals(infos[46])?"-1":infos[46]));//总市值
            tblStockDayInfos.setCirMarketVal(new BigDecimal("-".equals(infos[45])?"-1":infos[45]));//流通市值
            //jQuery17202780265590235217_1518327732639(
            // {"Comment":[],"Value":["1","600707",
            // (2)"彩虹股份","8.41","8.40","8.38","8.36","8.35","8.42","8.43","8.44",
            // (11)"8.45","8.46","1422","10","1","2","1665","19","159","23","254","50",
            // (23)"9.14","7.48","8.26","8.03","-0.05",(28)"8.09","-0.60",(30)"8.43","111431",
            // (32)"7.63","121",(昨收)"8.31","8943万","1.12","1.51","-","55209","56223",
            // （41）"71.98","2595",（43）"1.46","1",（45）"6079671537",（46）"29640100008","0|0|0|0|0","0|0|0|0|0",
            // "2018-02-09 15:34:51","9.63","-","-"]})
        } catch (Exception e) {
            logger.info("读取网页异常{}",e.getMessage());
            return false;
        } finally {
            try {
                is.close();
                isr.close();
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
}
